from odoo import fields, models, api


class ProductTemplate(models.Model):
    _inherit = 'product.template'

    limit_purchase = fields.Boolean(string='限制采购单位', related='categ_id.limit_purchase', store=True)

    @api.onchange('uom_id', 'categ_id')
    def _onchange_uom_id_categ_id(self):
        if self.categ_id.limit_purchase and self.uom_po_id.category_id != self.uom_id.category_id:
            self.uom_po_id = False

    @api.model
    def recursive_bom_calculation(self, product_id, qty):
        result = {}
        bom = self.env['mrp.bom'].search([
            ('product_tmpl_id', '=', product_id.product_tmpl_id.id),
            ('type', '=', 'normal')
        ], limit=1)
        for bom_line in bom.bom_line_ids:
            product = bom_line.product_id
            quantity = bom_line.product_qty * qty / bom.product_qty
            if not product.product_tmpl_id.bom_ids:
                if product in result:
                    result[product]['qty'] += quantity
                else:
                    result[product] = {
                        'qty': quantity
                    }
            sub_result = self.recursive_bom_calculation(product, quantity)
            if sub_result:
                result.update(sub_result)
        return result
